//
//  GoodDetailViewController.m
//  B2C
//
//  Created by xiaowu on 2017/7/31.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "GoodDetailViewController.h"
// cell
#import "GoodTitlePriceCell.h"
#import "GoodStandardCell.h"
#import "GoodInfoServiceCell.h"
#import "GoodCommentTitleCell.h"
#import "GoodCommentCell.h"
#import "GoodDetailBottomView.h"
#import "GoodServiceInfoView.h" // 服务信息
#import "GoodStandardView.h"    // 规格
#import "GoodDetailModel.h"     // detail
#import "GoodEvaluateListViewController.h"
#import "SKUManager.h" // SKU管理

#import "GoodEvaluateModel.h"
#import "PageNationModel.h"
#import "ShopcartOrderViewController.h"
#import "LoginViewController.h"
#import "ShoppingCartHomeViewController.h"

#define TestImageArr  @[@"http://pic.58pic.com/58pic/16/38/45/03i58PICDKP_1024.jpg",@"http://pic5.nipic.com/20091222/2905177_131009095824_2.jpg",@"http://img.sucai.redocn.com/attachments/images/201201/20120109/20111229_b786e39d3c820e367af8G5BwN8lSdvxX.jpg",@"http://pic.58pic.com/58pic/16/38/47/29Y58PICtyW_1024.jpg"]

@interface GoodDetailViewController ()<BHInfiniteScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource,DZNEmptyDataSetDelegate, UIScrollViewDelegate, UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *tableHeaderView;
@property (nonatomic, strong) UIView *tableFooterView;
@property (nonatomic, strong) BHInfiniteScrollView *bannerView;

@property (nonatomic, strong) GoodTitlePriceCell *titleCell;
@property (nonatomic, strong) GoodStandardCell *standardCell;
@property (nonatomic, strong) GoodInfoServiceCell *infoServiceCell;
@property (nonatomic, strong) GoodCommentTitleCell *commentTitleCell;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *messageButton;
@property (weak, nonatomic) IBOutlet GoodDetailBottomView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewTopLayout;

@property (nonatomic, strong) UIView *webViewHeader;
@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) GoodDetailModel *detailModel;
@property (nonatomic, strong) NSMutableArray *goodEvaluateListArr;
// 刷新选中的属性
@property (nonatomic, strong) GoodsAttributePriceModel *responsePriceModel;
// 选中的属性
@property (nonatomic, strong) NSMutableArray *selectArr;
@end

@implementation GoodDetailViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _titleCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodTitlePriceCell" owner:self options:nil] firstObject];
        _standardCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodStandardCell" owner:self options:nil] firstObject];
        _infoServiceCell = [[GoodInfoServiceCell alloc] init];
        _commentTitleCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodCommentTitleCell" owner:self options:nil] firstObject];
        _detailModel = [[GoodDetailModel alloc] init];
        _goodEvaluateListArr = [NSMutableArray array];
        _responsePriceModel = nil;
        _selectArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureUI];
//    [self showFirstView];
    self.tableView.hidden = YES;
    
    // tableView 偏移20/64适配
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.scrollViewTopLayout.constant = -[self getNavAndStatusHeight];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self showFirstView];
    
    [self loadNewData];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setNavigationBarAlpha:0.0 animation:NO];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.tableView.frame = self.scrollView.bounds;
    self.webViewHeader.frame = CGRectMake(0, self.scrollView.height + 64, self.scrollView.width, 40);
    self.webView.frame = CGRectMake(0, self.scrollView.height + 64 + self.webViewHeader.height, self.scrollView.width, self.scrollView.height - 64 - self.webViewHeader.height);
    
    self.scrollView.contentSize = CGSizeMake(self.scrollView.width, 2 * self.scrollView.height);

}

- (void)configureUI {
    [self.scrollView addSubview:self.tableView];
    [self.scrollView addSubview:self.webViewHeader];
    [self.scrollView addSubview:self.webView];
    self.scrollView.backgroundColor = [UIColor backgroundColor];
    self.scrollView.delegate = self;
    
    self.view.backgroundColor = [UIColor backgroundColor];
    self.tableView.backgroundColor = [UIColor backgroundColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.estimatedRowHeight = 44;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"GoodCommentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentCell"];
    
    [self responseBlock];
    [self reloadUI];
}

- (void)reloadUI {
    self.tableView.hidden = NO;
    // 重置已选中的属性
    [self setSelectArrIfExist];
    // 把无库存的priceitem 去除
    self.detailModel.goodsattribute = [SKUManager getSKUCountPriceItem:self.detailModel.goodsattribute];
    
    for (UIView *view in self.tableHeaderView.subviews) {
        if ([view isKindOfClass:[BHInfiniteScrollView class]]) {
            [view removeFromSuperview];
        }
    }
    
    _bannerView = [BHInfiniteScrollView infiniteScrollViewWithFrame:CGRectMake(0, 0, self.tableView.width, self.tableView.width) Delegate:self ImagesArray:[self.detailModel getImgsUrl] PlageHolderImage:PlaceholderImagePictures InfiniteLoop:YES];
    
    _bannerView.dotSize = 6;
    _bannerView.dotSpacing = 5;
    _bannerView.pageControlAlignmentOffset = CGSizeMake(0, 10);
    _bannerView.dotColor = [UIColor yellowLineColor];
    _bannerView.selectedDotColor = [UIColor whiteColor];
    
    [self.tableHeaderView addSubview:self.bannerView];
    self.tableHeaderView.frame = CGRectMake(0, 0, self.tableView.width, self.tableView.width);
    
    self.tableView.tableHeaderView = self.tableHeaderView;
    self.tableView.tableFooterView = self.tableFooterView;
    [self.tableView reloadData];
    
    [self.bottomView setBottomValueWithCollect:self.detailModel.iscollection andCartCount:self.detailModel.shopcartcount];
}

- (void)showFirstView {
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self setNavigationBarAlpha:0.0 animation:YES];

    self.backButton.hidden = NO;
    self.messageButton.hidden = YES;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(disMissSelf)];
    leftItem.tintColor = [UIColor colorWithHex:0x030303 alpha:1.0];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.navigationItem.title = @"";
}

- (void)showSecondView {
//    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self setNavigationBarAlpha:1.0 animation:YES];

    self.backButton.hidden = YES;
    self.messageButton.hidden = YES;
    
    [self showBackButtonItem];
    
    self.navigationItem.title = self.detailModel.gname;
    
    if (self.webView.request.URL.absoluteURL.absoluteString.length > 0) {
        return;
    }
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.detailModel.gdetails]]];

}

- (NSString *)getAllStandardName:(NSArray *)arr {
    NSString *str = @"";
    
    if (self.responsePriceModel) {
        for (GoodAttributeValueModel *model in self.selectArr) {
            str = [NSString stringWithFormat:@"%@%@ ", str, model.taname];
        }
        return str;
    }
    for (GoodAttributeModel *model in arr) {
        str = [NSString stringWithFormat:@"%@%@ ", str, model.ganame];
    }
    return str;
}

- (BOOL)checkLogin {
    if (![UserInfo shareInstance].isLogin) {
        __weak typeof(self) weakSelf = self;
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:loginVC];
        loginVC.loginSuccess = ^{
            [weakSelf loadNewData];
        };
        [self presentViewController:nav animated:YES completion:nil];
        return NO;
    }
    return YES;
}

- (void)disMissSelf {
    if(self.navigationController) {
        if (self.gbarcode.length > 0) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)setSelectArrIfExist {
    if (self.selectArr.count > 0) {
        for (GoodAttributeModel *attributeModel in self.detailModel.attribute) {
            for (GoodAttributeValueModel *valueModel in attributeModel.twoattribute) {
                for (GoodAttributeValueModel *selectValueModel in self.selectArr) {
                    if ([valueModel.taid isEqualToString:selectValueModel.taid]) {
                        valueModel.isSelected = YES;
                    }
                }
            }
        }
    }
}

#pragma mark - Action
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)messageButtonClick:(id)sender {
    
}

- (void)presentActivityVC {
    
    
    UIActivityViewController *activityView = [[UIActivityViewController alloc] initWithActivityItems:@[@"这里是标题", [UIImage imageNamed:@"logo"],[UIImage imageNamed:@"logo"],[UIImage imageNamed:@"logo"],[UIImage imageNamed:@"logo"],[UIImage imageNamed:@"logo"]] applicationActivities:nil];
    activityView.excludedActivityTypes = @[UIActivityTypeMessage,
                                           UIActivityTypeMail,
                                           UIActivityTypePrint,
                                           UIActivityTypeCopyToPasteboard,
                                           UIActivityTypeAssignToContact,
                                           UIActivityTypeSaveToCameraRoll,
                                           UIActivityTypeAddToReadingList,
                                           UIActivityTypePostToFlickr,
                                           UIActivityTypePostToVimeo,
                                           UIActivityTypeAirDrop,
                                           UIActivityTypeOpenInIBooks];
    [self presentViewController:activityView animated:YES completion:nil];
    
    
//    UIActivityTypePostToFacebook
//    UIActivityTypePostToTwitter
//    UIActivityTypePostToWeibo
//    UIActivityTypePostToTencentWeibo
}

- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.bottomView.block = ^(NSInteger index) {
        switch (index) {
            case 0:{
//                [weakSelf presentActivityVC];
//                return;
                // 加入收藏
                if (weakSelf.detailModel.iscollection) {
                    [weakSelf cancelCollect];
                } else {
                    [weakSelf addToCollect];
                }
            } break;
            case 1:{
                // 购物车
                ShoppingCartHomeViewController *cartVC = [[ShoppingCartHomeViewController alloc] init];
                cartVC.type = 1;
                [self.navigationController pushViewController:cartVC animated:YES];
            } break;
            case 2:{
                // 加入购物车
                [GoodStandardView showGoodStandardViewWithTitle:self.detailModel.gname
                                                          price:self.detailModel.price
                                                          count:@"1"
                                                       imageURL:self.detailModel.gimg
                                          goodAttributeModelArr:self.detailModel.attribute
                                    goodsAttributePriceModelArr:self.detailModel.goodsattribute
                                         goodsPriceTaidModelArr:self.detailModel.goodspricetaid
                                                           type:GoodStandardViewTypeForAddCart
                                                      needReset:NO
                                                          block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
                                                              // 修改外面的原价和现价，以及选中的属性名字
                                                              weakSelf.responsePriceModel = priceModel;
                                                              weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
                                                              [weakSelf.tableView reloadData];
                                                              if (buttonIndex == 0) {
                        [weakSelf addToShopCart:count goodsAttributePriceModel:priceModel];
                    }
                }];
            } break;
            case 3:{
                // 立即购买
                [GoodStandardView showGoodStandardViewWithTitle:self.detailModel.gname
                                                          price:self.detailModel.price
                                                          count:@"1"
                                                       imageURL:self.detailModel.gimg
                                          goodAttributeModelArr:self.detailModel.attribute
                                    goodsAttributePriceModelArr:self.detailModel.goodsattribute
                                         goodsPriceTaidModelArr:self.detailModel.goodspricetaid
                                                           type:GoodStandardViewTypeForBuy
                                                      needReset:NO
                                                          block:^(NSInteger buttonIndex, NSMutableArray <GoodAttributeValueModel *> *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
                                                              // 修改外面的原价和现价，以及选中的属性名字
                                                              weakSelf.responsePriceModel = priceModel;
                                                              weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
                                                              [weakSelf.tableView reloadData];
                                                              if (buttonIndex == 1) {
                                                                  [weakSelf jumpToBuy:priceModel withCount:count withTwoAttribute:arr];
                                                              }
                }];
            } break;
                
            default:
                break;
        }
    };
}

#pragma mark - Network
- (void)loadNewData {
    if (self.gid.length > 0) {
        [self loadGoodDetail]; // gid获取商品详情
    } else if (self.gbarcode.length > 0) {
        [self loadGoodDetailWithGbarcode]; // 通过二维码获取商品详情
    }
}

- (void)loadGoodDetail {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.gid forKey:@"gid"];
    
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Goods_Detail parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            weakSelf.detailModel = [GoodDetailModel mj_objectWithKeyValues:data];

            [weakSelf getEvaluateList]; // 获取评论列表
            [weakSelf reloadUI];
        } else if (code && [code isEqualToString:@"215"]) {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf disMissSelf];
            });
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:NO];
}

- (void)loadGoodDetailWithGbarcode {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.gbarcode forKey:@"gbarcode"];
    
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Goods_Detail_Code parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            weakSelf.detailModel = [GoodDetailModel mj_objectWithKeyValues:data];

            [weakSelf getEvaluateList]; // 获取评论列表
            [weakSelf reloadUI];
        } else if (code && [code isEqualToString:@"215"]) {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf disMissSelf];
            });
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:NO];

}

- (void)getEvaluateList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    [parameters safeSetObject:@"1" forKey:@"pageNumber"];
    [parameters safeSetObject:@"3" forKey:@"pageSize"];
    
    __weak typeof(self) weakSelf = self;
//    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Evaluate parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.goodEvaluateListArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                GoodEvaluateModel *model = [GoodEvaluateModel mj_objectWithKeyValues:modelDic];
                [weakSelf.goodEvaluateListArr addObject:model];
            }
            [weakSelf.tableView reloadData];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
    } isNeedCache:NO];

}

// 加入购物车
- (void)addToShopCart:(NSString *)count goodsAttributePriceModel:(GoodsAttributePriceModel *)priceModel {
    if (![self checkLogin]) {
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    [parameters safeSetObject:priceModel.gaid forKey:@"gaid"];
//    [parameters safeSetObject:@"" forKey:@"devicecode"];
    [parameters safeSetObject:count forKey:@"number"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Add_Shopcart parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            [weakSelf loadNewData];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        
    }];
}

// 跳转到 购买
- (void)jumpToBuy:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count withTwoAttribute:(NSMutableArray <GoodAttributeValueModel *> *)twoAttribute {
    
    if (![self checkLogin]) {
        return;
    }
    
    ShopcartModel *model = [[ShopcartModel alloc] init];
    model.gnumber = self.detailModel.gnumber;
    model.gname = self.detailModel.gname;
    model.gid = self.detailModel.gid;
    model.gextension = self.detailModel.gextension;
    model.gimg = self.detailModel.gimg;
    model.number = count;
    model.gaoldprice = priceModel.gaoldprice;
    model.gaprice = priceModel.gaprice;
    model.gastock = priceModel.gastock;
    model.gaid = priceModel.gaid;
    model.attribute = [NSMutableArray arrayWithArray:self.detailModel.attribute];
    model.goodsattribute = [NSMutableArray arrayWithArray:self.detailModel.goodsattribute];
    model.goodspricetaid = [NSMutableArray arrayWithArray:self.detailModel.goodspricetaid];
    
    
    //    @property (nonatomic, copy) NSString *scid;         // 购物车id
    //    @property (nonatomic, assign) BOOL isshelves;       // 是否上架（0否1是）
    //    @property (nonatomic, strong) NSMutableArray<AttributeModel *> *twoattribute; // 属性
    
    
    ShopcartOrderViewController *orderVC = [[ShopcartOrderViewController alloc] init];
    orderVC.tableArray = [NSMutableArray arrayWithObject:model];
//    orderVC.priceAttStr = [NSString stringWithFormat:@"%.2f",priceModel.gaprice.floatValue * count.integerValue];
    orderVC.type = ShopcartOrderTypeGoods;
    [self.navigationController pushViewController:orderVC animated:YES];
}

- (void)addToCollect {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Add_Collect parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            self.detailModel.iscollection = YES;
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        [weakSelf reloadUI];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

- (void)cancelCollect {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Cancel_Collect parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            self.detailModel.iscollection = NO;
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        [weakSelf reloadUI];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    } else if (section == 1) {
        return self.goodEvaluateListArr.count + 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [self.titleCell setValueForCell:self.detailModel.gname subTitle:self.detailModel.gextension price:(self.responsePriceModel.gaprice.length > 0 ? self.responsePriceModel.gaprice : self.detailModel.price) oldPrice:(self.responsePriceModel.gaoldprice.length > 0 ? self.responsePriceModel.gaoldprice : self.detailModel.oldprice)];
            return self.titleCell;
        } else if (indexPath.row == 1) {
            
            self.standardCell.titleLabel.text = @"选择: ";
            self.standardCell.contentLabel.text = [self getAllStandardName:self.detailModel.attribute];// @"颜色,型号";
            return self.standardCell;
        } else if (indexPath.row == 2) {
            [self.infoServiceCell setValueForCellWithStrArr:[self.detailModel getGtotsStr]];
            return self.infoServiceCell;
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            [self.commentTitleCell.heartView setImageViewWithPoint:self.detailModel.escore.floatValue withType:HeartTypeForNormal];
            return self.commentTitleCell;
        } else {
            GoodEvaluateModel *model = [self.goodEvaluateListArr safeObjectAtIndex:indexPath.row - 1];
            GoodCommentCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
            [commentCell setValueForCellWithContent:model.econtent headUrl:model.mimg time:model.createtime nickNamek:model.mnickname point:model.escore withImages:[model getImgsUrl] isAnonymous:model.isanonymous];
            
            commentCell.picturesCell.block = ^(UIImageView *imageView, NSInteger index) {
                [weakSelf showPicture:imageView index:index urls:[model getImgsUrl]];
            };

            return commentCell;
        }
    }
    
    return [[UITableViewCell alloc] init];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
        } else if (indexPath.row == 1) {
            return 44;
        } else if (indexPath.row == 2) {
            return 40;
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 44;
        } else {
            GoodEvaluateModel *model = [self.goodEvaluateListArr safeObjectAtIndex:indexPath.row - 1];
            return [GoodCommentCell getHeightWithContent:model.econtent withImages:[model getImgsUrl]];
        }
    }
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 5;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            __weak typeof(self) weakSelf = self;
            [GoodStandardView showGoodStandardViewWithTitle:self.detailModel.gname
                                                      price:self.detailModel.price
                                                      count:@"1"
                                                   imageURL:self.detailModel.gimg
                                      goodAttributeModelArr:self.detailModel.attribute
                                goodsAttributePriceModelArr:self.detailModel.goodsattribute
                                     goodsPriceTaidModelArr:self.detailModel.goodspricetaid
                                                       type:GoodStandardViewTypeForAll
                                                  needReset:NO
                                                      block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
                                                          // 修改外面的原价和现价，以及选中的属性名字
                                                          weakSelf.responsePriceModel = priceModel;
                                                          weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
                                                          [weakSelf.tableView reloadData];
                                                          
                                                          if (buttonIndex == 0) {
                                                              [weakSelf addToShopCart:count goodsAttributePriceModel:priceModel];
                                                          } else if (buttonIndex == 1) {
                                                              [weakSelf jumpToBuy:priceModel withCount:count withTwoAttribute:arr];
                                                          }
                                                      }
             ];
        }else if (indexPath.row == 2) {
            [GoodServiceInfoView showGoodServiceInfoViewWithTitles:self.detailModel.gtots];
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            // 查看全部
            GoodEvaluateListViewController *evaluateListVC = [[GoodEvaluateListViewController alloc] init];
            evaluateListVC.gid = self.detailModel.gid;
            [self.navigationController pushViewController:evaluateListVC animated:YES];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        NSLog(@"scrollViewDidScroll-tableview y :%f", self.tableView.mj_offsetY);
    } else if (scrollView == self.scrollView) {
        NSLog(@"scrollViewDidScroll-scrollView y :%f", self.scrollView.mj_offsetY);
    } else if (scrollView == self.webView.scrollView) {
        NSLog(@"scrollViewDidScroll-webView y :%f", self.webView.scrollView.mj_offsetY);
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        NSLog(@"scrollViewWillBeginDragging-tableview y :%f", self.tableView.mj_offsetY);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        NSLog(@"scrollViewDidEndDecelerating-tableview y :%f", self.tableView.mj_offsetY);
    } else if (scrollView == self.scrollView) {
        CGFloat y = scrollView.contentOffset.y;
        CGFloat page = y / self.scrollView.height;
        if (page > 0.3) {
            [self showSecondView];
            NSLog(@"1");
        } else {
            [self showFirstView];
            NSLog(@"0");
        }
        NSLog(@"scrollViewDidEndDecelerating: %f", page);
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        NSLog(@"scrollViewWillBeginDecelerating-tableview y :%f", self.tableView.mj_offsetY);
    }
}

#pragma mark - BHInfiniteScrollViewDelegate
- (void)infiniteScrollView:(BHInfiniteScrollView *)infiniteScrollView didSelectItemAtIndex:(NSInteger)index {
    
    [self showPicture:infiniteScrollView index:index urls:[self.detailModel getImgsUrl]];
}

#pragma mark - Getters
- (UIView *)tableHeaderView {
    if (!_tableHeaderView) {
        _tableHeaderView = [[UIView alloc] init];
    }
    return _tableHeaderView;
}

- (UIView *)tableFooterView {
    if (!_tableFooterView) {
        _tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        _tableFooterView.backgroundColor = [UIColor backgroundColor];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        titleLabel.text = @"上拉查看图文详情";
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = TextNormalFont12;
        titleLabel.textColor = [UIColor grayTextColor];
        
        [_tableFooterView addSubview:titleLabel];
    }
    return _tableFooterView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [_tableView clearExtendCellLine];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    }
    return _tableView;
}

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
//        _webView.backgroundColor = [UIColor backgroundColor];
//        _webView.scrollView.backgroundColor = [UIColor backgroundColor];
        _webView.delegate = self;
        _webView.scrollView.delegate = self;
    }
    return _webView;
}

- (UIView *)webViewHeader {
    if (!_webViewHeader) {
        _webViewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        _webViewHeader.backgroundColor = [UIColor backgroundColor];
        
        // 线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake((ScreenWidth - 90) * 0.5 - 45, 0, 90 + 90, 0.5)];
        lineView.backgroundColor = [UIColor grayTextColor];
        lineView.center = _webViewHeader.center;

        // 整体挡住view
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake((ScreenWidth - 90) * 0.5, 0, 90, 40)];
        backView.backgroundColor = [UIColor backgroundColor];
        backView.center = _webViewHeader.center;
        
        // 图片
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"detail_pic"]];
        imageView.frame = CGRectMake(0, 0, 16, 16);
        imageView.center = CGPointMake(0 + 16, backView.centerY);
        
        // 文字
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageView.right, 0, 60, 40)];
        titleLabel.text = @"图文详情";
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = TextNormalFont12;
        titleLabel.textColor = [UIColor grayTextColor];
        titleLabel.backgroundColor = [UIColor backgroundColor];
        
        
        [backView addSubview:imageView];
        [backView addSubview:titleLabel];
        [_webViewHeader addSubview:lineView];
        [_webViewHeader addSubview:backView];
    }
    return _webViewHeader;
}


@end
